package com.linkdood.app.service;

import com.linkdood.app.service.impl.UploadFileServiceImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.io.*;

/**
 * 文件写入单元测试
 */
@ExtendWith(MockitoExtension.class)
public class UploadFileServiceUT {

    @Mock
    private AccountUploadFileService accountUploadFileService;

    @Mock
    private ZipService zipService;

    private UploadFileServiceImpl uploadFileService;

    @BeforeEach
    public void setup() {
        uploadFileService = new UploadFileServiceImpl(accountUploadFileService, zipService);
    }

    /**
     * 文件写入单元测试
     */
    @Test
    public void testWriteFile() {
        // 首先建立原始文件
        String originFilePath = "test.txt";
        // 目标文件
        String targetFilePath = "target.txt";
        // 文件内容如下，写入到原始文件中，之后和目标文件内容比对即可
        String fileContent = "Test write file! 我是中文！我是中文！我是中文！";

        File originFile = new File(originFilePath);
        try (FileWriter originWriter = new FileWriter(originFile);) {
            if (!originFile.exists()) {
                originFile.createNewFile();
            }
            // 写入文件
            originWriter.write(fileContent);
        } catch (Exception e) {
            Assertions.fail(e.getMessage());
        }
        // 测试后端写文件的逻辑
        File targetFile = new File(targetFilePath);
        long offset = 0;
        try (InputStream inputStream = new FileInputStream(originFile)) {
            uploadFileService.writeFile(targetFile, inputStream, offset);
        } catch (Exception e) {
            Assertions.fail(e.getMessage());
        }
        // 检测数据有没有刷新到目标文件
        if (!targetFile.isFile()) {
            Assertions.fail("targetAbsoluteFile is not file");
        }
        try (FileReader targetFileReader = new FileReader(targetFile);) {
            char[] buf = new char[6];
            int len;
            StringBuilder readTxt = new StringBuilder();
            while ((len = targetFileReader.read(buf)) != -1) {
                readTxt.append(new String(buf, 0, len));
            }
            Assertions.assertEquals(readTxt.toString(), fileContent);
        } catch (Exception e) {
            Assertions.fail(e.getMessage());
        } finally {
            // 最后删除文件
            originFile.delete();
            targetFile.delete();
        }
    }
}
